package com.ibm.member.service.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ibm.member.api.MemberService;
import com.ibm.member.common.exception.MemberException;
import com.ibm.member.common.util.RandomUtil;
import com.ibm.member.dao.MemberDao;
import com.ibm.member.model.MemberVO;

@Service("memberService")
public class MemberServiceImpl implements MemberService {

    @Autowired
    public MemberDao memberDao;

    /** CUS-01-01 创建个人客户 */
    @Override
    public MemberVO registerMember(MemberVO member) throws MemberException {
        memberDao.create(member);
        return member;
    }

    /** CUS-02-01 查询个人客户基本信息 */
    @Override
    public List<MemberVO> findMember(MemberVO member) {
        return memberDao.find(member);
    }

    /** 验证手机格式 */
    public boolean validateMobileNum(String mobileNum) {
        return StringUtils.isNumeric(mobileNum) && mobileNum.length() == 11 && mobileNum.startsWith("1");
    }

    /** 验证邮箱是否存在 */
    public boolean isEmailExsit(String email) {
        MemberVO member = new MemberVO();
        member.setEmail(email);
        if (memberDao.get(member) != null)
            return true;
        return false;
    }

    /** 验证个人客户手机号是否存在 */
    public boolean isMobileExsit(String mobileNum) {
        MemberVO member = new MemberVO();
        member.setMobileNum(mobileNum);
        if (memberDao.get(member) != null)
            return true;
        return false;
    }

    /** 验证个人客户用户名是否存在 */
    public boolean isUserNameExsit(String userName) {
        MemberVO member = new MemberVO();
        member.setUserName(userName);
        if (memberDao.get(member) != null)
            return true;
        return false;
    }

    /** 判断身份信息是否存在 */
    public boolean isCertExists(String certType, String certNo) {
        MemberVO member = new MemberVO();
        member.setCertType(certType);
        member.setCertNo(certNo);
        if (memberDao.get(member) != null)
            return true;
        return false;
    }

    /** 生成唯一用户名 */
    public String genUserName() {
        String userName = null;
        boolean isRepeated = true;
        do {
            userName = RandomUtil.randomString(20);
            isRepeated = isUserNameExsit(userName);
        } while (isRepeated);
        return userName;
    }
}